package com.itheima.hmshopping.app.config;


import com.itheima.hmshopping.entity.UmsAdmin;
import com.itheima.hmshopping.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class TokenInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        //1、获取请求头
        String[] split = request.getHeader("Authorization").split(" ");
        String token=split[1];
        //2、使用工具类，判断token是否有效
        Claims claimsBody = JwtUtil.getClaimsBody(token);
        int verifyToken = JwtUtil.verifyToken(claimsBody);

        //3、如果token失效，返回状态码401，拦截 
        if(verifyToken==1||verifyToken==2) {
            response.setStatus(401);
            return false;
        }
        //4、如果token正常可用，放行
        //解析token，获取id，构造User对象，存入Threadlocal
        Claims claims = JwtUtil.getClaimsBody(token);
        Integer id = (Integer) claims.get("id");

        UmsAdmin user = new UmsAdmin();
        user.setId(Long.valueOf(id));
        UserHolder.set(user);

        return true;
    }
}
